package com.qingfeng.client.service;

import com.qingfeng.client.bean.OrderStore;
import com.qingfeng.client.bean.TradeQueueMsg;
import com.qingfeng.client.util.TradeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * 用户未支付取消订单队列服务器
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/1/9 5:41 下午
 */
@Slf4j
@Service
public class DealQueueService {

    //收货延迟时间，单位毫秒
    @Value("${autoRecvExpire}")
    private long recvExpire;
    @Value(("${autoCloseExpire}"))
    private long closeTradeExpire;

    @Autowired
    private OrderService orderService;

    //订单的队列
    public static DelayQueue<TradeQueueMsg> overQueue= new DelayQueue<TradeQueueMsg>();

    public void initQueue(){
        log.info("初始化队列，待收货，待评价，自动转换为下一个状态");
        initRecv();
        initClose();
    }

    /**
     * 初始化待收货自动处理队列
     */
    private void initRecv(){
        List<OrderStore> recvOrders = orderService.getByStat(TradeEnum.TRADE_WAIT_RECV.getCode());
        for (OrderStore orderStore:recvOrders){
            long expire = recvExpire;
            if (orderStore.getSendTime()!=null){
                expire = expire - (System.currentTimeMillis() - (orderStore.getSendTime() * 1000L));
            }
            addQueueMsg(1,orderStore.getId(),expire);
        }
    }

    /**
     * 初始化关闭订单自动处理队列
     */
    private void initClose(){
        List<OrderStore> closeOrders = orderService.getByStat(TradeEnum.TRADE_FINISH.getCode());
        for (OrderStore orderStore:closeOrders){
            long expire = recvExpire;
            if (orderStore.getFinishTime()!=null){
                expire = expire - (System.currentTimeMillis() - (orderStore.getFinishTime() * 1000L));
            }
            addQueueMsg(1,orderStore.getId(),expire);
        }
    }


    /**
     * 添加到消息队列
     * @param type 消息类型
     * @param orderStoreId 订单id
     */
    private void addQueueMsg(int type,Long orderStoreId,long expire){
        TradeQueueMsg tradeQueueMsg = new TradeQueueMsg();
        tradeQueueMsg.setType(type);
        tradeQueueMsg.setOrderStoreId(orderStoreId);
        tradeQueueMsg.setExpiredTime(expire);
        overQueue.add(tradeQueueMsg);
    }

    /**
     * 添加待收货队列
     * @param orderStoreId
     */
    public void addRecv(Long orderStoreId){
        addQueueMsg(1,orderStoreId,recvExpire);
    }

    /**
     * 添加到待关闭队列
     * @param orderStoreId
     */
    public void addClose(Long orderStoreId){
        addQueueMsg(2,orderStoreId,closeTradeExpire);
    }



    public void startDealQueue(){
        new Thread(){
            @Override
            public void run() {
                System.out.println("=============开启订单处理线程===========");
                while (true){
                    TradeQueueMsg queueMsg = null;
                    try {
                        // 没有满足延时的元素 用poll返回 null
                        // 没有满足延时的元素 用take会阻塞
                        queueMsg =  overQueue.take();
                        if (queueMsg.getType()==1){
                            orderService.dealRecvOrder(queueMsg.getOrderStoreId());
                        }else if (queueMsg.getType()==2){
                            orderService.dealCloseOrder(queueMsg.getOrderStoreId());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }



}
